<template>
  <view class="page-items">
	  <!-- <view wx:if="{{noData}}" class="nodata">没有搜到相关商品，为你推荐以下商品</view> -->
		<block v-for="(item,index) in items" :key="index">
			<view style="padding-left:10px" @click="goShopDe(item.shopId)">{{item.shopName}}</view>
		    <view class="gsss">
				<u-scroll-list>
					<view v-for="data in item.restShopDishes" @click="goGoodsDe(data)" class="deitem">
						<image v-if="data.dimg" mode="aspectFill" style="width:100%;height:5rem;border-radius: 20rpx;" :src="uploadFilePath+data.dimg"></image>
						<image v-else mode="aspectFill" style="width:100%;height:5rem;"  :src="default_img"></image>
						<view class="dnames">{{data.dname}}</view>
					</view>
				</u-scroll-list>
		    </view>
		</block>
		<u-popup :show="ggpopup" :round="10" mode="center" closeOnClickOverlay  @open="openTset" @close="ggpopup = false">
			<view style="padding:20upx">
				<view>{{rowData.dname}}</view>
				<view v-for="(item,index) in specData" style="display:flex;margin-top:20upx">
					<view>{{item.speType}}:</view>
					<view v-for="(it,idx) in item.detail" style="display:flex;padding-left:10upx;">
						<u-button :color="`${it.speId == item.checkVal?'#f9ae3d':'#666'}`" size="mini" :text="it.speTypeItem" style="padding-left:10upx;color:#000000" @click="choseSpec(idx,it.speId)"></u-button>
					</view>
				</view>
				<view style="margin:20upx;font-size:1rem">已选规格：{{checkSpec}}</view>
				<u-button type="warning" text="加入购物车" size="small" @click="addCart(2)"></u-button>
			</view>
		</u-popup>
		<u-modal :show="delState" :title="dtitle" @confirm="clearCart" @cancel="closeMd" :content='content' showConfirmButton showCancelButton></u-modal>
  </view>
</template>
<script>
  import Config from '@/util/index.js'
  import {
   getGoodsByRant,queryGoodAll
  } from '@/api/goods'
  import {
   saveCart,cartList,delCart
  } from '@/api/cart'
  import {
   saveCollect,updataCollect,collectList,delCollect
  } from '@/api/collect'
  import Page from '../pages/student/cart/index.vue'
  export default {
    name: "Page",
	components: {
		Page
	},
	data() {
	  return {
		items:[],
		content:'是否清空购物车',
		dtitle:'清空购物车',
		specData:[],
		checkSpec:'',
		dishesname:'',
		rcode:'',
		boxVals:[],
		rowData:{},
		checkData:[],
		cartData:[],
		checkIdData:[],
		checked:true,
		delState:false,
		scode:'',
		default_img:'',
		shopId:'',
		total:0,
		numval:1,
		jbnum:2,
		activeBtn:0,
		cartPopup:false,
		noData:false,
		ggpopup:false,
		moreData:false,
	    uploadFilePath:''
	  }
	},
	onShow(){
		console.log("000")
		
	},
	onLoad(options) {
		console.log("111")
	},
	created(){
		this.uploadFilePath = Config.get('apiUrl')
		this.default_img = this.picUrl + 'goods.png'
		this.getPageData("","",1,10);	
	},
	methods:{
		closeMd(){
			this.delState = false
		},
		goShopDe(id){
			uni.navigateTo({
				url: `shop/index?mid=${id}`
			})
		},
		goGoodsDe(data){
			// this.$navTo(`./goods/detail`, { goodsId })
			uni.navigateTo({
				url: `goods/detail?gid=${data.dishesId}`
			})
		},
		addCollect(row){
			let _this = this
			uni.getStorage({
				key: 'userifo',
				success: function (res) {
					let userIfo = JSON.parse(res.data)
					let params = {
						coId: null,
						deptId:_this.rcode,
						userId: userIfo.userId,
						dishesId: row.dishesId,
						isFlag: 1,
						createBy: row.createBy,
						createTime: row.createTime,
						updateBy: row.updateBy,
						updateTime: row.updateTime
					}
					saveCollect(params).catch(resx => {
						if(resx.data.code == 200){
							uni.showToast({
							  title:"收藏成功",
							  icon: 'none',
							  duration: 2000
							});
						}
					})
				},
			})
			
		},
		choseSpec(cid,id){
			this.activeBtn = cid
			this.specData.forEach((item,idx)=>{
				item.detail.forEach(it=>{			
					if(id == it.speId){
						item.checkVal = id
						this.checkData[idx] = it.speTypeItem
						this.checkIdData[idx] = it.speId
					}
				})
			})
			this.checkSpec = this.checkData.toString()
		},
		clearCart(){
			this.boxVals = []
			this.cartData.forEach((item)=>{
				this.boxVals.push(item.ocartId)
			})
			let params = this.boxVals.join(",")
			delCart(params).catch(res => {
				if(res.code == 200){
					uni.showToast({
					  title:"删除成功",
					  icon: 'none',
					  duration: 2000
					});
				}
			})
		},
		openTset(){},
		addCart(type){
			let _this = this
			uni.getStorage({
				key: 'userifo',
				success: function (res) {
					let userIfo = JSON.parse(res.data)
					//添加购物车
					let params = {
						ocartId:"",
						userId:userIfo.userId,
						shopId:_this.rowData.shopId,
						dishesId:_this.rowData.dishesId,
						dprice:_this.rowData.dprice,
						buyNum:1,
						deptId:_this.rcode,
						speName:_this.rowData.restShopDisheSpecs.length==0?"":_this.checkSpec,
						speIds:_this.rowData.restShopDisheSpecs.length==0?"":_this.checkIdData.toString(),
						isflag:1
					}
					if(_this.rowData.dprice){
						saveCart(params).catch(resp => {
							if(resp.data.code == 200){
								uni.showToast({
								  title:"加入成功",
								  icon: 'none',
								  duration: 2000
								});
								if(type==1){
									//直接加购物车
									let pas = {
										userId:params.userId
									}
									cartList(pas).catch(resx => {
										if(resx.data.code == 200){
											_this.cartData = resx.data.rows
										}
									})
								}
								_this.ggpopup = false
							}
						})
					}else{
						this.$message.info("该商品未定价，不能售卖")
					}
				}
			});		
		},
		changeSpec(row){
			this.rowData = row
			// this.specData = row.restShopDisheSpecs
			const groupBy = (array, key) => {
			  return array.reduce((result, currentItem) => {
				// 使用 key 的值作为分组的键
				const groupKey = currentItem[key];
				// 如果 result 中不存在这个键，则创建它
				if (!result[groupKey]) {
				  result[groupKey] = [];
				}
				// 将当前项添加到对应的分组中
				let obj = {
				  speId:currentItem.speId,
				  // speType:currentItem.speType,
				  speTypeItem:currentItem.speTypeItem,
				  spePrice:currentItem.spePrice,
				  isflag:parseInt(currentItem.isflag)
				}
				result[groupKey].push(obj);
				return result;
			  }, {});
			};
			let spcdata = row.restShopDisheSpecs
			let tdata = groupBy(spcdata, 'speType');
			let names = Object.keys(tdata)
			this.specData=[]
			for(let i=0;i<names.length;i++){
			  let xx = {
				dishesId:row.dishesId,
				speType:names[i],
				checkVal:"",
				detail:tdata[names[i]]
			  }        
			  this.specData.push(xx)
			}
			this.ggpopup = true
		},
		openCart(row){
			this.rowData = row
			this.addCart(1)
		},
		getPageData(name,type,sname,pnum,psize) {
			if(pnum==1){
				this.items = []
			}
			let _this = this
			uni.getStorage({
				key: 'deptdas',
				success: function (res) {
					let depts = JSON.parse(res.data)
					_this.scode = depts.scode
					_this.rcode = depts.rcode	
					console.log("_this.rcode",_this.rcode)
					let params = {
						deptId: _this.rcode,
						dname: name,
						dtype: type,
						shopName: sname,
						pageNum: pnum,
						pageSize: psize
					}
					queryGoodAll(params).catch(res => {
						if(res.data.rows.length > 0){
							const newList = res.data.rows
							_this.total = parseInt(res.data.total)
							if(_this.items.length < _this.total){
								_this.items = [..._this.items, ...newList]
							}else{
							  _this.moreData = true
							}
						}else{
							if(pnum==1){
							  _this.noData = true
							}
							_this.moreData = true
							uni.showToast({
							  title:"暂无数据",
							  icon: 'none',
							  duration: 2000
							});
						}
					})
				}
			})
		}
	}
  }
</script>
<style>
  .page-items{font-size:1rem;margin-top:10px}
  .deitem{width:200upx;height:6.5rem;margin-left:10px}
  .gsss{height:6.8rem;width:100%;padding:20rpx 0rpx;display: flex;overflow-x: auto;}
  .jsdiv{
	  width:90%;height:100upx;border-radius: 50px;border:1px solid #f5f5f5;box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5);display: flex;justify-content: space-between;
	  margin:20upx auto;
  }
  .dnames{font-weight:bold;font-size:0.8rem;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}
  .jbcss{width:15upx;margin-left:30px;position:absolute;z-index: 10;}
  .botcart{height:60upx;line-height:60upx;padding:20upx;display:flex;justify-content: space-between;border-bottom:1px solid #f5f5f5}
  .jxbtn{width:150upx;height:100upx;font-size:18px;line-height:100upx;text-align: center;
  background-color:#04743a;color:#fff;border-top-right-radius: 50px;border-bottom-right-radius: 50px;}
  .utag{width:auto;height:1rem;border: 1px solid #F66;font-size: 0.8rem;padding:0.2rem;border-radius: 10px;margin-right:0.5rem}
</style>
